package com.tens.tens_base.service;

import com.tens.tens_base.dao.LabelDao;
import com.tens.tens_base.pojo.Label;
import com.tens.tens_common.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * 标签业务逻辑类
 */
@Service
@Transactional
public class LabelService {

    @Autowired
    private LabelDao labelDao;

    @Autowired
    private IdWorker idWorker;

    /**
     * 查询所有标签
     * @return
     */
    public List<Label> findAll(){
        return labelDao.findAll();
    }

    /**
     * 根据id查询标签
     * @param id
     * @return
     */
    public Label findById(String id){
        return labelDao.findById(id).get();
    }

    /**
     * 添加标签
     * @param label
     */
    public void add(Label label){
        label.setId( idWorker.nextId() + "" );//设置id（雪花算法）
        labelDao.save(label);
    }

    /**
     * 修改标签
     * @param label
     */
    public void update(Label label){
        labelDao.save(label);
    }

    /**
     * 删除标签
     * @param id
     */
    public void deleteById(String id){
        labelDao.deleteById(id);
    }

    public List<Label> findSearch(Label label){
       return   labelDao.findAll(new Specification<Label>() {
           /**
            *
            * @param root 条件封装对象
            * @param criteriaQuery 关键字
            * @param criteriaBuilder 封装条件对象
            * @return
            */
                    @Override
                  public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                        List<Predicate> list = new ArrayList<>();
                        if(label.getLabelname() != null && !"".equals(label.getLabelname())){
                             Predicate predicate = criteriaBuilder.like(root.get("labelname").as(String.class), "%" + label.getLabelname() + "%");
                             list.add(predicate);
                        }
                        if(label.getState() != null && !"".equals(label.getState())){
                            Predicate predicate = criteriaBuilder.equal(root.get("state").as(String.class), label.getState());
                            list.add(predicate);
                        }
                        Predicate[] predicates = new Predicate[list.size()];
                        predicates = list.toArray(predicates);
                        return criteriaBuilder.and(predicates);
                     }
              });
    }

}
